// 在cashier.html的script部分整合以下功能
const cartHandler = {
    items: [],
    addItem(product) {
        const existItem = this.items.find(i => i.id === product.id);
        if (existItem) {
            existItem.quantity++;
        } else {
            this.items.push({
                ...product,
                quantity: 1,
                discount: 0
            });
        }
        this.updateUI();
    },
    
    updateUI() {
        // 更新小票和购物车列表
        this.renderReceipt();
        this.renderSummary();
    },
    
    renderReceipt() {
        const receipt = document.getElementById('receiptContainer');
        if (this.items.length === 0) {
            receipt.innerHTML = `<div class="text-center text-gray-500 py-10">等待扫描商品...</div>`;
            return;
        }
        
        let html = `
            <div class="receipt-header">
                <!-- 头部信息 -->
            </div>
            <table class="w-full text-sm mt-2">
                <thead>
                    <tr class="border-b">
                        <th class="text-left pb-2">商品</th>
                        <th class="text-right">单价</th>
                        <th class="text-right">数量</th>
                        <th class="text-right">小计</th>
                    </tr>
                </thead>
                <tbody>`;
                
        this.items.forEach(item => {
            html += `
                <tr class="border-b">
                    <td class="py-2">${item.name}</td>
                    <td class="text-right">${item.price.toFixed(2)}</td>
                    <td class="text-right">${item.quantity}</td>
                    <td class="text-right font-medium">¥${(item.price * item.quantity).toFixed(2)}</td>
                </tr>`;
        });
        
        receipt.innerHTML = html + `</tbody></table>` + this.renderFooter();
    },
    
    renderFooter() {
        const total = this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        return `
            <div class="mt-4 border-t pt-2">
                <div class="flex justify-between font-bold text-lg">
                    <span>总计:</span>
                    <span>¥${total.toFixed(2)}</span>
                </div>
            </div>`;
    }
};

// 绑定事件
document.querySelectorAll('.add-to-cart').forEach(btn => {
    btn.addEventListener('click', function() {
        const productId = this.dataset.productId;
        const product = products.find(p => p.id === productId);
        if (product) cartHandler.addItem(product);
    });
});
